const {app, BrowserWindow, ipcMain, dialog} = require('electron');
const DataStore = require('./renderer/musicDataStore');

const myStore=  new DataStore({
  name: 'MusicData'
});

class AppWindow extends BrowserWindow {
  constructor(config, fileLocation = 'index.html') {
    const basic = {
      width: 800,
      height: 600,
      webPreferences: {
        nodeIntegration: true
      }
    };
    const finalConfig = {...basic, ...config};
    super(finalConfig);
    this.loadFile(fileLocation);
    this.on('ready-on-show', () => {
      this.show();
    });
  }
}

let p = app.getPath('userData');

app.on('ready', () => {
  const mainWindow = new AppWindow({}, './renderer/index.html');

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.send('getTracks', myStore.getTracks());
  });

  ipcMain.on('add-music-window', () => {
    const addWindow = new AppWindow({
      width: 500,
      height: 400,
      parent: mainWindow
    }, './renderer/add.html');
  });

  ipcMain.on('open-music-file', (event) => {
    dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [
        {
          name: 'Music',
          extensions: ['mp3']
        }
      ]
    }, files => {
      if (files) {
        event.sender.send('selected-file', files);
      }
      console.log(files);
    })
  });

  ipcMain.on('add-tracks', (event, tracks) => {
    const updateTracks = myStore.addTracks(tracks).getTracks();
    mainWindow.send('selected-file', updateTracks);
  });

  ipcMain.on('delete-track', (event, id) => {
    const updatedTracks = myStore.deleteTrack(id).getTracks();
    mainWindow.send('getTracks', updatedTracks)
  });

});

